package JdbcTest.Jdbc;

import com.mysql.cj.jdbc.Driver;

import java.sql.*;

public class JdbcTest1 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet set = null;
        try {
            //注册驱动
            Driver driver = new Driver();
            DriverManager.registerDriver(driver);
            //获取数据库连接对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/temp?serverTimezone=UTC","root","1643006834");
            //获取数据库操作对象
            stmt = conn.createStatement();
            String sql = "select * from t_user";
            String sql1 = "insert into t_user(id,name,sex) values(4,'zs','男')";
            //执行Sql语句 executeQuery方法用来做查询操作
            set = stmt.executeQuery(sql);
            while(set.next()){
                String a1 = set.getString("id");
                String a2 = set.getString("name");
                String a3 = set.getString("sex");
                System.out.println(a1+"\t"+a2+"\t"+a3);
            }
            //executeUpdate方法用来做修改，插入，删除操作
            int num = stmt.executeUpdate(sql1);
            if(num > 0){
                System.out.println("数据插入成功,共"+num+"条");
            }else{
                System.out.println("数据插入失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (set != null) {
                try {
                    set.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
